package com.lilicould.service.impl;

import com.lilicould.dao.AccountDao;
import com.lilicould.dao.EmployeeDao;
import com.lilicould.entity.Account;
import com.lilicould.entity.Employee;
import com.lilicould.entity.Tenant;
import com.lilicould.service.AccountService;
import org.apache.ibatis.session.SqlSession;

import com.lilicould.util.MyBatisUtil;
import org.mindrot.jbcrypt.BCrypt;

import com.lilicould.util.UUIDUtile;

import java.io.ByteArrayOutputStream;


public class AccountServiceImpl implements AccountService {
    // 登录服务
    @Override
    public Account login(String username, String password) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        Account account = accountDao.selectAccountByUsername(username);
        if (account == null) return null; // 用户不存在
        if (BCrypt.checkpw(password, account.getPassword())) { // 密码校验正确
            return account;
        }else return null;
    }

    // 租户注册服务
    @Override
    public boolean registerTenant(Account account, Tenant tenant, String phone) {
        SqlSession sqlSession = null;
        try {
            // 获取数据库连接
            sqlSession = MyBatisUtil.getSqlSession();
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

            // 开启事务（禁用自动提交）
            sqlSession.getConnection().setAutoCommit(false);

            // 将密码进行加密
            String password = account.getPassword();
            password = BCrypt.hashpw(password, BCrypt.gensalt());
            account.setPassword(password);

            // 生成用户id
            String userId = UUIDUtile.generateOrderedId();
            account.setUserId(userId);
            tenant.setTenantId(userId);

            // 插入账户信息
            int accountResult = accountDao.insertAccount(account);
            if (accountResult <= 0) throw new RuntimeException("插入账户失败");

            // 插入租户信息
            int tenantResult = accountDao.insertTenant(tenant);
            if (tenantResult <= 0) throw new RuntimeException("插入租户失败");

            // 插入电话信息
            int phoneResult = accountDao.insertPhone(phone, userId);
            if (phoneResult <= 0) throw new RuntimeException("插入电话失败");

            // 所有操作成功，提交事务
            sqlSession.commit();
            return true;

        } catch (Exception e) {
            // 出现异常，回滚事务
            if (sqlSession != null) {
                try {
                    sqlSession.rollback();
                } catch (Exception ex) {
                    System.out.println("回滚事务失败");
                }
            }
            System.out.println(e.getMessage());
            return false;
        } finally {
            // 关闭资源
            if (sqlSession != null) {
                try {
                    sqlSession.close();
                } catch (Exception e) {
                    System.out.println("关闭资源失败");
                }
            }
        }
    }

    // 员工注册服务
    @Override
    public boolean registerEmployee(Account account, Employee employee, String roleId,String skill) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();

        // 自动生成用户id
        String userId = UUIDUtile.generateOrderedId();
        userId = String.format("EMPLOYEE_%s", userId);
        // 密码加密
        String password = BCrypt.hashpw(account.getPassword(), BCrypt.gensalt());
        account.setPassword(password);
        account.setUserId(userId);
        employee.setEmployeeId(userId);

        // 获取持久层接口
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);

        try {
            // 开启事务（禁用自动提交）
            sqlSession.getConnection().setAutoCommit(false);
            int accountResult = accountDao.insertAccount(account);
            if (!(accountResult > 0)) throw new Exception("插入账号失败");
            int employeeResult = employeeDao.insertEmployee(employee);
            if (!(employeeResult > 0)) throw new Exception("插入员工失败");
            int employeeHasRoleResult = employeeDao.insertEmployeeHasRole(employee.getEmployeeId(),roleId,skill);
            if (!(employeeHasRoleResult > 0)) throw new Exception("插入员工角色关系失败");
            sqlSession.commit();
            return true;
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }

    }

    // 验证用户名是否存在
    @Override
    public boolean checkUsername(String username) {
        SqlSession sqlSession = null;
        try {
            // 获取数据库连接
            sqlSession = MyBatisUtil.getSqlSession();
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

            // 检查用户名是否存在
            int count = accountDao.checkUsername(username);
            return count > 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    // 通过用户名查询租户
    @Override
    public Tenant selectTenantByUsername(String username) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
            return accountDao.selectTenantByUsername(username);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }

    // 通过用户名查询员工
    @Override
    public Employee selectEmployeeByUsername(String username) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
            return accountDao.selectEmployeeByUsername(username);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }

    // 删除账户
    @Override
    public boolean deleteAccount(String userId) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
            int result = accountDao.deleteAccount(userId);
            return result>0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    // 通过userId查询用户
    @Override
    public Account selectAccountById(String userId) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
            return accountDao.selectAccountById(userId);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }
}
